package com.monkey.luffer.springboot.demo.basis.kcc.s3cmd;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

public class UploadObjects implements S3Oper {

	@Override
	public void request(AmazonS3 s3, MyCmd cmd) {
		File base = new File(cmd.srcPath);
		base.getParentFile().mkdirs();
		highLevelUpload(base, s3, cmd);
	}

	@SneakyThrows
	private void highLevelUpload(File file, AmazonS3 s3, MyCmd myCmd) {
		if (!file.exists()){
			System.out.println("file " + file + " not exist");
			return;
		}
		if (file.isDirectory()){
			for (File f: file.listFiles()){
				highLevelUpload(f, s3, myCmd);
			}
		}else if (file.isFile()){
			String fileName = file.getName();
			String filePath = file.getParentFile().getAbsolutePath();
			String basePath = new File(myCmd.getSrcPath()).getAbsolutePath();
			String prefix = (StringUtils.equals(file.getAbsolutePath(), basePath)) ? "" : myCmd.getPrefix() +  filePath.replace(basePath, "");
			TransferManager tm = TransferManagerBuilder.standard()
					.withS3Client(s3)
					.build();
			String key = "";

			if ("null".equals(prefix)) {
				prefix = "";
			}

			if (StringUtils.isNotBlank(prefix)) {
				key = prefix + File.separator + fileName;
			} else {
				key = fileName;
			}

			PutObjectRequest request = new PutObjectRequest(myCmd.getBucket(), key, file);
			request.setGeneralProgressListener((progressEvent)->System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred()));
			// TransferManager processes all transfers asynchronously,
			// so this call returns immediately.
			Upload upload = tm.upload(request);

			// Optionally, you can wait for the upload to finish before continuing.
			upload.waitForCompletion();
		}
	}
}
